﻿using System.Threading;
using SystemModule;

namespace M2Server
{
    public class ServerEngine
    {
        private uint _runTimeTick = 0;
        private readonly Thread _serverThread;

        public ServerEngine()
        {
            _serverThread = new Thread(Execute);
            _serverThread.IsBackground = true;
        }

        public void Run()
        {
            _serverThread.Start();
        }

        private void Execute()
        {
            while (true)
            {
                if (M2Share.boStartReady)
                {
                    M2Share.RunSocket.Run();
                    M2Share.FrmIDSoc.Run();
                    M2Share.UserEngine.Run(); // 引擎启动
                    ProcessGameRun();
                    M2Share.FrmMsgClient.Run();
                }
                M2Share.n4EBD1C++;
                if ((HUtil32.GetTickCount() - M2Share.g_dwRunTick) > 250)
                {
                    M2Share.g_dwRunTick = HUtil32.GetTickCount();
                    M2Share.nRunTimeMin = M2Share.n4EBD1C;
                    if (M2Share.nRunTimeMax > M2Share.nRunTimeMin)
                    {
                        M2Share.nRunTimeMax = M2Share.nRunTimeMin;
                    }
                    M2Share.n4EBD1C = 0;
                }
                Thread.Sleep(50);
            }
        }

        private void ProcessGameRun()
        {
            HUtil32.EnterCriticalSection(M2Share.ProcessHumanCriticalSection);
            try
            {
                M2Share.UserEngine.PrcocessData();
                M2Share.g_EventManager.Run();
                M2Share.RobotManage.Run();
                if (HUtil32.GetTickCount() - _runTimeTick <= 10000) return;
                _runTimeTick = HUtil32.GetTickCount();
                M2Share.g_GuildManager.Run();
                M2Share.g_CastleManager.Run();
                lock (M2Share.g_DenySayMsgList)
                {
                    for (int i = M2Share.g_DenySayMsgList.Count - 1; i >= 0; i--)
                    {
                        if (M2Share.g_DenySayMsgList.Count <= 0)
                        {
                            break;
                        }
                        //if (HUtil32.GetTickCount() > ((uint)M2Share.g_DenySayMsgList[i]))
                        //{
                        //    M2Share.g_DenySayMsgList.RemoveAt(i);
                        //}
                    }
                }
            }
            finally
            {
                HUtil32.LeaveCriticalSection(M2Share.ProcessHumanCriticalSection);
            }
        }
    }
}
